<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-17 14:47:38
component:     transfer
Copyright © YourCompanyName All rights reserved
-->
<template>
  <el-dialog
    :destroy-on-close="true"
    title="转派"
    v-model="isVisible"
    @close="handleClose"
    width="800px"
  >
    <div style="display: flex; align-items: center; justify-content: center">
      <el-form ref="formRef" :rules="rules" label-position="left" :model="form">
        <el-form-item prop="deptId" label="部门">
          <el-select v-model="form.deptId" placeholder="请选择部门" style="width: 300px">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="roleId" label="角色">
          <el-select
            :options="roleList"
            v-model="form.roleId"
            placeholder="请选择角色"
            style="width: 300px"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id"
              :label="item.nickname"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleSave">转派</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { defineEmits, defineProps, ref, watch } from 'vue'
import { distributeCustomer, simpleListDept, SimpleListDeptRes } from '@/api/customer'
import { contactSimpleAllListUser, SimpleListUserRes } from '@/api/order/create'
import { ElForm } from 'element-plus'

const message = useMessage() // 消息弹窗

// 定义组件的 props
interface Props {
  visible: boolean
  ids: number[]
}

// 获取 props 和 emits
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void // 添加 success 事件
}>()
// ----------------------------- 表单 -----------------------------
const loading = ref(false)
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const form = ref({
  deptId: undefined,
  roleId: undefined
})
const rules = reactive({
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
})
// 部门角色options
const deptList = ref<SimpleListDeptRes[]>([])
const roleList = ref<SimpleListUserRes[]>([])

// 获取部门角色options
const simpleListDeptFn = async () => {
  try {
    const res = await simpleListDept()
    deptList.value = res
  } catch (e) {
    console.error(e)
  }
}
const simpleListUserFn = async () => {
  try {
    const deptId = form.value.deptId
    if (!deptId) {
      return
    }
    roleList.value = await contactSimpleAllListUser({
      deptId
    })
  } catch (e) {
    console.error(e)
  }
}
// 提交
const handleSave = async () => {
  loading.value = true
  try {
    await formRef?.value?.validate()
    const res = await distributeCustomer({
      ids: props.ids,
      ownerUserId: form.value.roleId || ''
    })
    if (res.code === 0) {
      message.success('分配成功')
      handleClose()
      emit('success')
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
// 监听部门的值请求角色option
watch(
  () => form.value.deptId, // 监听 deptId
  async (newValue) => {
    if (newValue === undefined) {
      // 如果新值是 undefined，不触发请求
      roleList.value = []
      return
    }
    await simpleListUserFn() // 正确调用函数
  }
)
onMounted(() => {
  simpleListDeptFn()
})
// ==================== 弹窗  ====================

// 局部状态变量，用于管理弹窗的可见性
const isVisible = ref<boolean>(props.visible)

// 监视 props.visible 的变化，以更新局部状态
watch(
  () => props.visible,
  async (newValue) => {
    isVisible.value = newValue
  }
)

// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
}
</script>

<style scoped>
/* 您的样式 */
</style>
